package com.xs.ahoi.hcxs.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.xs.ahoi.hcxs.R;
import com.xs.ahoi.hcxs.dao.AppUserInfo;
import com.xs.ahoi.hcxs.dao.BookDao;
import com.xs.ahoi.hcxs.dao.ConfigDao;
import com.xs.ahoi.hcxs.dao.DBHelper;
import com.xs.ahoi.hcxs.tencent.QQManager;
import com.xs.ahoi.hcxs.ui.dialog.DialogLoading;
import com.xs.ahoi.hcxs.utils.*;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import okhttp3.Call;

import static com.xs.ahoi.hcxs.utils.Constants.SERVER_HOST;

/**
 * author: ahoi
 * date: 2018/6/27 17:24
 * description: 我的
 */
public class UserFragment extends Fragment {

    @BindView(R.id.tvNickName)
    public TextView tvNickName;
    @BindView(R.id.login)
    public LinearLayout login;
    @BindView(R.id.loginInfo)
    public LinearLayout loginInfo;
    @BindView(R.id.ivUserHead)
    public ImageView ivUserHead;
    @BindView(R.id.tvBackupTime)
    public TextView tvBackupTime;


    private QQManager qqManager;
    private QQManager.LoginCallback loginCallback;

    private Unbinder unbinder;
    private FragmentActivity context;
    private ConfigDao configDao;

    private DialogLoading dialogLoading;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_user, container, false);
        unbinder = ButterKnife.bind(this, view);
        context = getActivity();
        initListener();
        init();
        return view;
    }

    private void init() {
        configDao = ConfigDao.getInstance();
        dialogLoading = new DialogLoading(context);
        qqManager = QQManager.getInstance().setLoginCallback(loginCallback);

        // 更新上次备份时间
        updateBackupTime();

        // 更新view
        updateView();
    }

    // 初始化监听器
    private void initListener() {
        // 登录操作回调
        loginCallback = new QQManager.LoginCallback() {
            @Override
            public void showL(String msg) {
                showLoading(msg);
            }

            @Override
            public void hideL() {
                hideLoading();
            }

            @Override
            public void updateV() {
                updateView();
            }
        };
    }

    // 更新上次备份时间
    private void updateBackupTime() {
        long backupTime = configDao.getBackupTime();
        if (backupTime == 0) {
            tvBackupTime.setText("未备份");
        } else {
            String time = DateUtil.time2String(backupTime, DateUtil.FORMAT_YMD_HMS);
            tvBackupTime.setText("上次备份：" + time);
        }
    }

    @OnClick({R.id.backupDB, R.id.restoreDB, R.id.loginQQ, R.id.loginWX,
            R.id.loginInfo, R.id.errorLog, R.id.daka})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.backupDB:
                if (DBHelper.backupDB()) {
                    // 更新上次备份时间
                    configDao.setBackupTime(DateUtil.getTime());
                    updateBackupTime();
                    ToastUtil.show("数据库备份成功");
                } else {
                    ToastUtil.show("数据库备份失败");
                }
                break;
            case R.id.restoreDB:
                if (!FileUtil.isFile(Constants.DB_BACKUP_PATH)) {
                    ToastUtil.show("未找到备份文件");
                } else {
                    if (DBHelper.restoreDB()) {
                        ToastUtil.show("数据库恢复成功");
                    } else {
                        ToastUtil.show("数据库恢复失败");
                    }
                }
                break;
            case R.id.loginQQ:
                qqManager.login(this);
                break;
            case R.id.loginWX:
//                startActivity(new Intent(context, WXEntryActivity.class));
                break;
            case R.id.loginInfo:
                qqManager.loginOut(this);
                login.setVisibility(View.VISIBLE);
                loginInfo.setVisibility(View.GONE);
                tvNickName.setText("");
                break;
            case R.id.errorLog:
                BookDao.getInstance().saveOrUpdate(Constants.ERROR_LOG_PATH);
                ToastUtil.show("已导入至书架");
                break;
            case R.id.daka:
                OkHttpUtils.get().url(SERVER_HOST + "/admin/jd/daka").build().execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastUtil.show("打卡失败");
                        LogUtil.e("打卡失败", e);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ToastUtil.show("打卡成功");
                    }
                });
                break;
        }
    }

    @Override
    public void onDestroy() {
        ButterKnifeUtil.unbind(unbinder);
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        qqManager.onActivityResult(requestCode, resultCode, data);
        hideLoading();
    }

    // 显示加载框
    private void showLoading(String msg) {
        dialogLoading.show(msg);
    }

    // 隐藏加载框
    private void hideLoading() {
        dialogLoading.dismiss();
    }

    // 更新view
    private void updateView() {
        AppUserInfo user = qqManager.getUser();
        if (user == null) {
            login.setVisibility(View.VISIBLE);
            loginInfo.setVisibility(View.GONE);
        } else {
            loginInfo.setVisibility(View.VISIBLE);
            login.setVisibility(View.GONE);

            // 设置昵称和头像
            tvNickName.setText(user.getNickName());
            RequestOptions options = new RequestOptions();
            options.circleCrop();
            Glide.with(context).load(user.getFigureUrl()).apply(options).into(ivUserHead);
        }
    }
}
